const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const fs = require('fs')
const path = require('path')

const app = express()
const PORT = process.env.PORT || 8080
// 兼容从任何工作目录启动，始终定位到当前文件同级的 data.json
const DB_PATH = path.join(__dirname, 'data.json')

app.use(cors())
app.use(express.json())
app.use(morgan('dev'))

function ensureDB(){
  if(!fs.existsSync(DB_PATH)){
    const seed = { users: [], songs: [], favs: [], history: [] }
    fs.writeFileSync(DB_PATH, JSON.stringify(seed, null, 2))
  }
}
function readDB(){ ensureDB(); return JSON.parse(fs.readFileSync(DB_PATH, 'utf-8')) }
function writeDB(db){ fs.writeFileSync(DB_PATH, JSON.stringify(db, null, 2)) }

app.get('/health', (_,res)=> res.json({ ok: true }))

app.post('/login', (req,res)=>{
  const { phone } = req.body || {}
  const db = readDB()
  
  // 如果数据库中没有用户，创建一个默认用户
  if (db.users.length === 0) {
    db.users.push({ id: 1, phone: "10000000000", name: "默认用户", token: "mock-token" })
    writeDB(db)
  }
  
  const user = db.users.find(u=> u.phone===phone) || db.users[0]
  res.json({ token: user.token, user: { id: user.id, name: user.name } })
})

app.get('/songs', (req,res)=>{
  const db = readDB()
  res.json(db.songs)
})

// 兼容错误路径 /song → /songs
app.get('/song', (req,res)=>{
  const db = readDB()
  res.json(db.songs)
})

app.get('/search', (req,res)=>{
  const { q } = req.query
  if(!q){ return res.json([]) }
  // 简化搜索功能，返回本地歌曲
  const db = readDB()
  const songs = db.songs.filter(song => 
    song.name.toLowerCase().includes(q.toLowerCase()) || 
    song.artist.toLowerCase().includes(q.toLowerCase())
  )
  res.json(songs)
})

app.get('/favs', (req,res)=>{ const db = readDB(); res.json(db.favs) })
app.post('/favs/toggle', (req,res)=>{
  const { song } = req.body
  const db = readDB()
  const idx = db.favs.findIndex(i=> i.id===song.id)
  if(idx>-1) db.favs.splice(idx,1); else db.favs.unshift(song)
  writeDB(db)
  res.json(db.favs)
})

app.get('/history', (req,res)=>{ const db = readDB(); res.json(db.history) })
app.post('/history/add', (req,res)=>{
  const { song } = req.body
  const db = readDB()
  const filtered = db.history.filter(i=> i.id!==song.id)
  filtered.unshift({ ...song, ts: Date.now() })
  db.history = filtered.slice(0,50)
  writeDB(db)
  res.json(db.history)
})

app.listen(PORT, ()=> console.log(`Backend running at http://localhost:${PORT}`))


